//
//  BRStationListViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/24.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRStationListViewController.h"
#import "BRStatilListTableViewCell.h"
#import "BRStationsDetailViewController.h"

#import "BRStaionListHeader.h"

//#import "Lottie-Swift.h"

@interface BRStationListViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,QMUITextFieldDelegate>
{
 
    NSInteger _offset;
//    QMUITextField *_searchTF;
//    BOOL _isSearch;
}

@property (nonatomic,assign) NSInteger selType;

@property (nonatomic,strong) BRStaionListHeader *headerView;
@property (nonatomic,strong) BRStaionListSubHeader *subHeader;

@property (nonatomic,strong) NSArray *stationList;  // 筛选后的列表
@property (nonatomic,strong) NSArray *allSitesList; // 所有站点列表（用于筛选）

@property (nonatomic,strong) NSArray *searchList;

@property (nonatomic,strong) UIView *headDownView;

@end

@implementation BRStationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    
    [self addKeyboardNotifaction];
    [self addRefreshActionForView:self.tableView];
    [self addLoadMoreActionForView:self.tableView];
    self.tableView.mj_footer.hidden = YES;
    [self requestNearStation:self.location page:_offset];
    
//    self.tableView.mj_header.backgroundColor = UIColorMakeWithHex(@"#EEEEF5");
    self.headDownView = [[UIView alloc] init];
    self.headDownView.backgroundColor = kColorBGEC;
    //    [self.tableView insertSubview:self.headDownView atIndex:0];/
    [self.tableView.mj_header insertSubview:self.headDownView atIndex:0];
    [self.headDownView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.height.mas_equalTo(300);
        make.left.offset(14);
        make.right.offset(-14);
    }];
//    NSString *patch = [BRThemeManage br_patchStr:@"Loading" type:@"json"];
//    CompatibleAnimationView *lotV = [[CompatibleAnimationView alloc] initWithUrl:[NSURL fileURLWithPath:patch]];
//    lotV.frame = CGRectMake(0, 0, 160, 160);
//    lotV.loopAnimationCount = -1;
//    lotV.backgroundColor = kColorShadow(0.1);
//    
//    [self.view addSubview:lotV];
//    lotV.center = self.view.center;
//    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [lotV play];
//    });
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)handleListRefreshAction {
    _offset = 0;
    [self requestNearStation:self.location page:_offset];
}

- (void)handleListLoadMoreAction {
//    if (_isSearch) return;
    _offset += 20;
    [self requestNearStation:self.location page:_offset];
}

#pragma mark - request --
- (void)requestNearStation:(CLLocationCoordinate2D)location page:(NSInteger)offset {
    
    // 使用全局位置信息
    CLLocationCoordinate2D globalLocation;
    if ([BRTools respondsToSelector:@selector(br_getGlobalLocation)]) {
        globalLocation = [BRTools br_getGlobalLocation];
    } else {
        // 如果方法不存在，使用(0,0)，等待真实定位
        globalLocation = CLLocationCoordinate2DMake(0, 0);
    }
    CGFloat lng = globalLocation.longitude;
    CGFloat lat = globalLocation.latitude;
    
    // 使用新接口 V2
    NSString *urlStr = [BRAPI stationNearV2:lng lat:lat distance:5 total:200];
    
    [self.tableView ly_startLoading];
    [[BRRequestManager shared] GET:urlStr params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [self.tableView ly_endLoading];
        
        if (self->_offset == 0) {
            // 重置列表
                self.stationList = @[];
                self.tableView.mj_footer.hidden = NO;
        }
        
        // 解析新接口返回的数据
        // BRRequestManager 已经处理了直接返回数组的情况，统一包装成字典格式
        NSArray *dataArray = nil;
        if ([dataDict[@"data"] isKindOfClass:[NSArray class]]) {
            // 从 data 字段获取数组数据
            dataArray = dataDict[@"data"];
        } else {
            // 兼容处理：如果 data 字段不存在或格式错误
            dataArray = @[];
            NSLog(@"⚠️ 站点列表数据格式错误，data字段不存在或不是数组");
        }
        
        NSArray *allSites = [BRStationListModel mj_objectArrayWithKeyValuesArray:dataArray];
        
        // 保存所有站点数据（用于切换tab时筛选）
        if (self->_offset == 0) {
            self.allSitesList = allSites;
        }
        
        // 前端筛选逻辑
        NSArray *filteredSites = [self getFilteredSites:self.allSitesList ?: allSites];
        
        // 合并数据（新接口一次性返回所有数据，不需要分页）
        if (self->_offset == 0) {
            self.stationList = filteredSites;
        } else {
            // 如果是加载更多，但由于新接口一次性返回，这里通常不会执行
            self.stationList = [self.stationList arrayByAddingObjectsFromArray:filteredSites];
        }
        
        // 新接口一次性返回所有数据，隐藏加载更多
            self.tableView.mj_footer.hidden = YES;
        
        [self.tableView reloadData];
        [self showBREmptyView];
        [self handleEndRefreshForView:self.tableView];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self.tableView ly_endLoading];
        self.tableView.mj_footer.hidden = YES;
        [self showBRErrorView];
        [self handleEndRefreshForView:self.tableView];
    }];
}

// 根据tab筛选数据（前端筛选）
- (NSArray *)getFilteredSites:(NSArray *)allSites {
    switch (self.selType) {
        case 0: {
            // rent: 可租借 - 营业中且有可借充电宝
            return [allSites filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BRStationListModel *site, NSDictionary<NSString *,id> * _Nullable bindings) {
                return site.open && site.depotBorrow > 0;
            }]];
        }
        case 1: {
            // return: 可归还 - 营业中且有空置位置
            return [allSites filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BRStationListModel *site, NSDictionary<NSString *,id> * _Nullable bindings) {
                return site.open && site.depotEmpty > 0;
            }]];
        }
        case 2:
        default: {
            // all: 全部
            return allSites;
        }
    }
}

- (void)setSelType:(NSInteger)selType {
    _selType = selType;
    self.subHeader.itemIndex = selType;
    
    // 如果已经有数据，直接筛选，不需要重新请求
    if (self.allSitesList && self.allSitesList.count > 0) {
        NSArray *filteredSites = [self getFilteredSites:self.allSitesList];
        self.stationList = filteredSites;
        [self.tableView reloadData];
        [self showBREmptyView];
    } else {
        // 如果还没有数据，则重新请求
    _offset = 0;
    [self requestNearStation:self.location page:_offset];
    }
}


#pragma mark - 键盘监听
- (void)addKeyboardNotifaction{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//键盘将要显示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];//键盘将要消失
}

#pragma mark - 键盘将要出现
- (void)keyboardWillShow:(NSNotification *)notification{
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification{
    
    
//    if (_searchTF.text.length == 0) {
//        _isSearch = NO;
//        [self.tableView reloadData];
//    }
}

#pragma mark - TextField Delegate --
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
//    NSString *searchText = [self searchString:@"" new:textField.text];
//
//    [self searchStr:searchText];
//    if (textField.text.length > 0) {
//        _isSearch = YES;
//        [self requestNearStation:self.location page:0];
//
//    }else {
//        _isSearch = NO;
//        [self.tableView reloadData];
//    }
//
//    [textField endEditing:YES];
    
    return YES;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    NSString *searchText = [self searchString:textField.text new:string];
//    NSLog(@"textFieldShouldEndEditing = %@ , string = %@ , searchText = [%ld - %ld]",textField.text,string,range.location,range.length);
////    [self searchStr:searchText];
//    if (string.length + range.location == 0) {
//        _isSearch = NO;
//        [self.tableView reloadData];
//    }
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    
//    _isSearch = NO;
//    [self.tableView reloadData];
//
    return YES;
}

#pragma mark - table delegate --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    if (_isSearch) {
//        return self.searchList.count;
//    }
    return self.stationList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BRStatilListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRStatilListTableViewCell"];
//
//    BRStationListModel *model = _isSearch ? self.searchList[indexPath.row] : self.stationList[indexPath.row];
    BRStationListModel *model = self.stationList[indexPath.row];
    cell.dto  = model;
    WS(weakSelf);
    cell.locationClick = ^{
        // 使用全局位置作为起始位置
        CLLocationCoordinate2D globalLocation;
        if ([BRTools respondsToSelector:@selector(br_getGlobalLocation)]) {
            globalLocation = [BRTools br_getGlobalLocation];
        } else {
            // 如果方法不存在，使用默认位置（越南胡志明市）
            globalLocation = CLLocationCoordinate2DMake(10.8231, 106.6297);
        }
        CLLocationCoordinate2D myL = (weakSelf.location.latitude != 0 && weakSelf.location.longitude != 0) ? weakSelf.location : globalLocation;
        CLLocationCoordinate2D toL = CLLocationCoordinate2DMake(model.lat, model.lng);
        [BROpenURL openMap:myL toLocation:toL titleAddress:model.address ?: @""];
    };
    
    return cell;
}

-  (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BRStationsDetailViewController  *vc = [[BRStationsDetailViewController alloc] init];
    vc.dto = self.stationList[indexPath.row];
    
    // 使用全局位置
    CLLocationCoordinate2D globalLocation;
    if ([BRTools respondsToSelector:@selector(br_getGlobalLocation)]) {
        globalLocation = [BRTools br_getGlobalLocation];
    } else {
        // 如果方法不存在，使用(0,0)，等待真实定位
        globalLocation = CLLocationCoordinate2DMake(0, 0);
    }
    if (self.location.latitude != 0 && self.location.longitude != 0) {
    vc.lat = self.location.latitude;
    vc.lng = self.location.longitude;
    } else {
        vc.lat = globalLocation.latitude;
        vc.lng = globalLocation.longitude;
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - scroller --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 滑动监听
    

//    NSLog(@"%.2f",_headView.mj_h);
    CGFloat offsetY = scrollView.contentOffset.y;

    // 临界值150，向上拖动时变透明
    self.subHeader.hidden = offsetY <= 40;
    
    
}


#pragma mark - SET UI --
- (void)setUI {
    
    BRNavView *top = [self br_createTop:Localized(@"home_nearbyMaerchants")];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 12)];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(top.mas_bottom).offset(-12);
        make.left.right.bottom.offset(0);
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRStatilListTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRStatilListTableViewCell"];
    
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 56);
    self.tableView.tableHeaderView = self.headerView;
    
    [self.view addSubview:self.subHeader];
    [self.subHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(48);
        make.left.right.offset(0);
        make.bottom.equalTo(top.mas_bottom).offset(0);
    }];
    
    [self.view bringSubviewToFront:top];
    
    WS(weakSelf);
    self.headerView.itemSelBlock = ^(NSInteger index) {
        weakSelf.selType = index;
    };
    
//    self.headDownView = [[UIView alloc] init];
//    self.headDownView.backgroundColor = UIColorMakeWithHex(@"#EEEEF5");
////    [self.tableView insertSubview:self.headDownView atIndex:0];/
//    [self.tableView.backgroundView addSubview:self.headDownView];
//    [self.headDownView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self.tableView.mas_top).offset(0);
//        make.height.mas_equalTo(200);
//        make.left.offset(14);
//        make.right.offset(-14);
//    }];
//
    
}

- (BRStaionListHeader *)headerView {
    
    if (_headerView == nil) {
        _headerView = [[BRStaionListHeader alloc] init];
    }
    return _headerView;
}

- (BRStaionListSubHeader *)subHeader {
    
    if (_subHeader == nil) {
        _subHeader = [[BRStaionListSubHeader alloc] init];
        _subHeader.hidden = YES;
    }
    return _subHeader;
}


//- (UIImage *)navigationBarBackgroundImage {
//    return [UIImage qmui_imageWithColor:UIColor.qd_backgroundColor];
//}

- (BOOL)preferredNavigationBarHidden {
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
